<template>
    <div class="container">
        <el-row :gutter="10">
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12" :offset="6">
                <div class="usercard">
                    <div class="usercard-left">
                        <el-avatar :size="100" :src="userInfo.avatarUrl" />
                        <div class="avatar-right">
                            <div class="name"> {{ userInfo.username }}</div>
                            <div class="description">简介：{{ userInfo.description }}</div>
                            <div class="sex">性别：{{ userInfo.sex == 1 ? '男' : '女' }}</div>
                            <div class="email">电子邮箱：{{ userInfo.email }}</div>
                            <div class="email">权限等级：{{ userInfo.roles }}</div>
                        </div>
                    </div>
                    <div class="usercard-right">
                        <el-button type="primary" @click="isEditMode = true">修改资料</el-button>
                        <el-button type="primary">退出登录</el-button>
                    </div>
                </div>
                <div class="commencard">
                    <template v-if="!isEditMode">
                        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                            <el-tab-pane label="帖子" name="first">
                                <div class="articlelist">
                                    <ul v-if="articleList.length > 0">
                                        <li class="article-item" v-for="item, index in articleList" :key="index"
                                            @click="gotDetail(item.articleid)">
                                            <div class="content">
                                                <div class="title">{{ item.title }}</div>
                                                <div class="contenttext" v-html="item.content"></div>
                                            </div>

                                            <div class="bottom">
                                                <div class="yes"><el-icon size="16">
                                                        <Pointer />
                                                    </el-icon>{{ item.like }}</div>
                                                <div class="comment">
                                                    <el-icon size="16">
                                                        <ChatDotSquare />
                                                    </el-icon>
                                                    {{ item.comments.length }}
                                                </div>
                                                <div @click.stop="copyText(item.articleid)" class="comment"><el-icon
                                                        size="16">
                                                        <Share />
                                                    </el-icon>分享</div>
                                            </div>
                                        </li>
                                    </ul>
                                    <el-empty v-else description="这里什么都没有" />
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="评论" name="second">
                                <div class="commentlist">
                                    <ul v-if="commentList.length > 0">
                                        <li class="comment-item" v-for="item, index in commentList" :key="index"
                                            @click="gotDetail(item.article.articleid)">
                                            <div class="title">文章标题：{{ item.article.title }}</div>
                                            <div class="content">
                                                <div class="text">
                                                    回复：{{ item.content }}
                                                </div>
                                                <div style="width: 20px;height:20px;background:#00000000" @click.stop>
                                                    <el-popconfirm @click="confirmdetele(index, item.commentid)"
                                                        class="box-item" title="要删除这条评论吗？" placement="left">
                                                        <template #reference>
                                                            <el-icon size="20">
                                                                <Delete />
                                                            </el-icon>
                                                        </template>
                                                    </el-popconfirm>
                                                </div>

                                            </div>
                                        </li>
                                    </ul>
                                    <el-empty v-else description="这里什么都没有" />
                                </div>

                            </el-tab-pane>
                            <el-tab-pane label="收藏" name="third">
                                <ul v-if="collectList.length > 0">
                                    <li class="collect-item" v-for="item, index in collectList" :key="index"
                                        @click="gotDetail(item.articleid)">
                                        <div class="user">
                                            <el-avatar class="avatar" :size="100" :src="item.user.avatarUrl" />
                                            <div class="right">
                                                <div class="username">{{ item.user.username }}</div>
                                                <div class="time">{{ item.create_time }}</div>
                                            </div>
                                        </div>
                                        <div class="content">
                                            <div class="title">文章标题：{{ item.title }}</div>

                                            <div class="contenttext" v-html="item.content">
                                            </div>

                                        </div>
                                    </li>
                                </ul>
                                <el-empty v-else description="快去收藏吧~" />
                            </el-tab-pane>
                            <el-tab-pane label="关注" name="fourth">
                                <div class="focuslist">
                                    <ul v-if="focusList.length > 0">
                                        <li class="focus-item" v-for="item, index in focusList" :key="index">
                                            <div class="focus-item-left">
                                                <el-avatar :size="50" :src="item.avatarUrl" />
                                                <div class="avatar-right">
                                                    <div class="name">{{ item.username }}</div>
                                                    <div class="desc">{{ item.description }}</div>
                                                </div>
                                            </div>
                                            <el-button @click="switchfocus(index, item.userid, 'switchfocus')"
                                                type="primary" :plain="item.isfocus">
                                                {{ item.isfocus ? '已关注' : '关注' }}
                                            </el-button>
                                        </li>
                                    </ul>
                                    <el-empty v-else description="您没有关注任何人" />
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="粉丝" name="fifth">
                                <div class="focuslist">
                                    <ul v-if="fanList.length > 0">
                                        <li class="focus-item" v-for="item, index in fanList" :key="index">
                                            <div class="focus-item-left">
                                                <el-avatar :size="50" :src="item.avatarUrl" />
                                                <div class="avatar-right">
                                                    <div class="name">{{ item.username }}</div>
                                                    <div class="desc">{{ item.description }}</div>
                                                </div>
                                            </div>
                                            <el-button @click="switchfocus(index, item.userid, 'switchfans')"
                                                type="primary" :plain="item.isfocus">
                                                {{ item.isfocus ? '已关注' : '回关' }}
                                            </el-button>
                                        </li>
                                    </ul>
                                    <el-empty v-else description="您没有粉丝" />
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </template>
                    <template v-else>
                        <el-card class="edit-user-card">
                            <template #header>
                                <div class="card-header">
                                    <span>编辑个人信息</span>
                                </div>
                            </template>
                            <el-form :model="editForm" :rules="rules" ref="formRef" label-width="80px">
                                <el-form-item label="头像">
                                    <el-upload :action="uploadUrl" :with-credentials="true" list-type="picture-card"
                                        :on-success="handleAvatarSuccess">
                                        <el-icon>
                                            <Plus />
                                        </el-icon>
                                        <template #file="{ file }">
                                            <div>
                                                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                                                <span class="el-upload-list__item-actions">
                                                    <span class="el-upload-list__item-preview"
                                                        @click="handlePictureCardPreview(file)">
                                                        <el-icon><zoom-in /></el-icon>
                                                    </span>
                                                    <span v-if="!disabled" class="el-upload-list__item-delete"
                                                        @click="handleDownload(file)">
                                                        <el-icon>
                                                            <Download />
                                                        </el-icon>
                                                    </span>
                                                    <span v-if="!disabled" class="el-upload-list__item-delete"
                                                        @click="handleRemove(file)">
                                                        <el-icon>
                                                            <Delete />
                                                        </el-icon>
                                                    </span>
                                                </span>
                                            </div>
                                        </template>
                                    </el-upload>
                                    <el-dialog v-model="dialogVisible">
                                        <img w-full :src="dialogImageUrl" alt="Preview Image" class="preview_image" />
                                    </el-dialog>
                                </el-form-item>
                                <el-form-item label="用户名" prop="username">
                                    <el-input v-model="editForm.username" />
                                </el-form-item>
                                <el-form-item label="简介" prop="description">
                                    <el-input v-model="editForm.description" type="textarea" />
                                </el-form-item>
                                <el-form-item label="性别" prop="sex">
                                    <el-radio-group v-model="editForm.sex">
                                        <el-radio label="1">男</el-radio>
                                        <el-radio label="0">女</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item label="邮箱" prop="email">
                                    <el-input v-model="editForm.email" />
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="onEditSubmit">保存</el-button>
                                    <el-button @click="onEditCancel">取消</el-button>
                                </el-form-item>
                            </el-form>
                        </el-card>
                    </template>
                </div>
            </el-col>
        </el-row>

    </div>
</template>

<script setup>
import { commonAjax } from '@/util/request.js'
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import clipboard from 'clipboard';
import { useRouter } from 'vue-router'
const router = useRouter()

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const uploadUrl = ref(`${Config.serverUrl}/upload/images`)
const imageUrl = ref('')
const activeName = ref('first')
const collectList = ref([])
const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
const focusList = ref([])
const fanList = ref([])
const articleList = ref([])
const isEditMode = ref(false)
const formRef = ref(null)
const editForm = ref({})
const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
}
const gotDetail = (articleid) => {
    console.log('articleid', articleid);

    router.push({
        path: '/detail',
        query: { articleid: articleid }
    })
}
const getuserDatail = () => {
    let _this = this;
    return new Promise((resolve, reject) => {
        commonAjax({
            url: `${Config.serverUrl}/user/findOne`,
            data: {
                userid: userInfo.value.userid
            },
        })
            .then((result) => {

                if (result && result.code == 200) {
                    userInfo.value = result.data
                    editForm.value = result.data
                }
                console.log(userInfo.value);
                console.log(editForm.value);

            })
            .catch((err) => {
                ElMessage.warning(err.message)
            });
    })
}
const getfans = () => {
    let _this = this;
    return new Promise((resolve, reject) => {
        commonAjax({
            url: `${Config.serverUrl}/focus/followers`,
            data: {
                userid: userInfo.value.userid
            },
        })
            .then((result) => {
                if (result && result.code == 200) {
                    fanList.value = result.data
                }
            })
            .catch((err) => {
                ElMessage.warning(err.message)
            });
    })
}
const getarticleList = () => {
    let _this = this;
    return new Promise((resolve, reject) => {
        commonAjax({
            url: `${Config.serverUrl}/article/findAllbyuser`,
            data: {
                userid: userInfo.value.userid
            },
        })
            .then((result) => {
                if (result && result.code == 200) {

                    result.data.forEach(element => {
                        var div = document.createElement("div");
                        div.innerHTML = element.content;
                        var text = div.textContent || div.innerText || "";
                        articleList.value.push({ ...element, content: text })
                    });

                }
            })
            .catch((err) => {
            });
    })
}
getfans()
getuserDatail()
getarticleList()
const commentList = ref([])

const copyText = (id) => {
    let text = 'http://111.229.148.175:5173/detail?articleid=' + id;
    navigator.clipboard.writeText(text);
    ElMessage('已复制到剪贴板！')
}
const getfocusList = () => {
    let _this = this;
    return new Promise((resolve, reject) => {
        commonAjax({
            url: `${Config.serverUrl}/focus/following`,
            data: {
                userid: userInfo.value.userid,
            },
        })
            .then((result) => {
                if (result && result.code == 200) {
                    result.data.forEach((item) => {
                        focusList.value.push({ ...item, isfocus: 1 })
                    })
                }
            })
            .catch((err) => {
                ElMessage.warning(err.message)
            });
    })
}
const switchfocus = (index, userid, switchfocus) => {
    console.log(userInfo.value);

    let _this = this;
    return new Promise((resolve, reject) => {
        commonAjax({
            url: `${Config.serverUrl}/focus/toggle`,
            data: {
                follower_id: userInfo.value.userid,
                following_id: userid
            },
        })
            .then((result) => {
                if (result && result.code == 200) {
                    if (switchfocus == 'switchfocus') {
                        focusList.value[index].isfocus = !focusList.value[index].isfocus
                    } else {
                        fanList.value[index].isfocus = !fanList.value[index].isfocus
                    }
                }
            })
            .catch((err) => {
                ElMessage.warning(err.message)
            });
    })
}
const confirmdetele = (index, id) => {
    let _this = this;
    return new Promise((resolve, reject) => {
        commonAjax({
            url: `${Config.serverUrl}/comment/detele`,
            data: {
                commentid: id
            },
        })
            .then((result) => {
                if (result && result.code == 200) {
                    commentList.value.splice(index, 1)
                }
            })
            .catch((err) => {
                ElMessage.warning(err.message)
            });
    })
}
const getcollectList = () => {
    let _this = this;
    return new Promise((resolve, reject) => {
        commonAjax({
            url: `${Config.serverUrl}/collect/findAllbyuserid`,
            data: {
                userid: userInfo.value.userid
            },
        })
            .then((result) => {
                if (result && result.code == 200) {
                    result.data.forEach(element => {
                        var div = document.createElement("div");
                        div.innerHTML = element.content;
                        var text = div.textContent || div.innerText || "";
                        collectList.value.push({ ...element, content: text })
                    });
                }
            })
            .catch((err) => {
                ElMessage.warning(err.message)
            });
    })
}
const getcommentList = () => {
    let _this = this;
    return new Promise((resolve, reject) => {
        commonAjax({
            url: `${Config.serverUrl}/comment/findAllbyuser`,
            data: {
                userid: userInfo.value.userid
            },
        })
            .then((result) => {
                if (result && result.code == 200) {
                    commentList.value = result.data
                }
            })
            .catch((err) => {
                ElMessage.warning(err.message)
            });
    })
}
getfocusList()
getcollectList()
getcommentList()
function handlePictureCardPreview(file) {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}
function handleDownload(file) {
    console.log(file)
}
function handleAvatarSuccess(file) {
    document.querySelector('.el-upload').style.display = "none"
    console.log('response', file);

    editForm.value.avatarUrl = Config.serverUrl + file.data.url
}
function handleRemove() {

}
function onEditSubmit() {
    formRef.value.validate(valid => {
        if (!valid) return
        let _this = this;
        commonAjax({
            url: `${Config.serverUrl}/user/update`,
            data: { ...editForm.value }
        }).then(res => {
            if (res && res.code === 200) {
                userInfo.value = { ...editForm.value }
                localStorage.setItem('userInfo', JSON.stringify(editForm.value))
                ElMessage.success('修改成功')
                isEditMode.value = false
            } else {
                ElMessage.error(res.msg || '修改失败')
            }
        }).catch((err) => {
            ElMessage.error(err.message)
        })
    })
}
function onEditCancel() {
    isEditMode.value = false
}
</script>

<style lang="scss" scoped>
@import './css/user.scss';

.edit-user-card {
    margin: 0 auto 24px auto;
    padding: 32px 24px;
}

::v-deep {
    .el-upload--picture-card {
        // display: none !important;
    }
}



// 美化列表页
.articlelist .article-item,
.commentlist .comment-item,
.focuslist .focus-item,
.collect-item {
    box-shadow: 0 1px 2px rgba(123, 123, 123, 0.06);
}

.articlelist .title,
.commentlist .title,
.collect-item .title {
    color: var(--theme_font_color);
    font-size: 1.1rem;
    margin-bottom: 8px;
}

.articlelist .content,
.commentlist .content {
    color: var(--theme_font_color);
}


.focuslist .focus-item-left {
    display: flex;
    align-items: center;
}

.focuslist .avatar-right {
    margin-left: 16px;
}
</style>